
using System;
using System.Collections;
using System.Diagnostics;
using System.ComponentModel;

using System.IO;

using CStock;


using CUtil;




namespace CStock
{
	
	/// <summary>
	/// Summary description for Portfolios.
	/// </summary>
    public class EconomyStatusCollection : StockObjectCollection, IEconomyStatusCollection
	{
        #region Constructor
        public EconomyStatusCollection()
            : base()
		{

            ResetPathFromConfiguration();
		}
        public override bool ResetPathFromConfiguration()
        {

            ProgramContext pc = ProgramContext.Instance;
            Debug.Assert(pc != null, "Initialize ProgramContext first ...");
            if (pc != null)
                this.path = pc.Configuration.Directories.EconomyStatusPath;
            return true;


        }
		#endregion	

		#region Class ArrayList Override

        public void CreateDefault()
        {
            this.items = new ArrayList();
            //this.economyStatusCollection = new EconomyStatusCollection();

            IEconomyStatus es = new EconomyStatus();
            es.Date = DateTime.Now;
            es.Percentage_Bonds_00 = 6;
            es.Percentage_Bonds_05 = 8;
            es.Percentage_Bonds_30 = 9;
            es.Percentage_Inflation = 5;

            es.Percentage_Overall = 10;
            es.Percentage_Productivity = 5;
            es.Percentage_Shares = 9;
            es.Percentage_InterestCB = 5;

            this.items.Add(es);
        }
    


		/// <summary>
		/// 
		/// </summary>
		/// <param name="obj"></param>
		/// <returns></returns>
		public int Add(object obj)
		{
			IEconomyStatus newPortfolio = (EconomyStatus)obj;
			
            if (this.Items.Count <= 0)
			{
                //if it is empty - add the portfolio
				this.items.Add(newPortfolio);
				return 0;
			}
			else
			{
                //check if the portfolio is already there!
				if (!this.items.Contains(newPortfolio))
				{
                    int index = this.Items.Count;
                    for (int i = 0; i < this.Items.Count; i++)
                    {
                        IEconomyStatus listPortfolio = (IEconomyStatus)this[i];
                        if (newPortfolio != listPortfolio)
                        {
                            index = i;
                            break;
                        }
                    }
					this.Items.Insert(index,newPortfolio);
					//OnChanged(EventArgs.Empty);
					return index;
				}
				else
				{
                    //the portfolio is already in the list!
                    Debug.Assert(false, "EconomyStatus", "Error adding EconomyStatus - already in the list " + newPortfolio.Name);
					return -1;
				}
			}
		}
      

		public int IndexOf(object obj)
		{
			return this.items.IndexOf(obj);
		}
		#endregion



		#region Implementation
		
		/// <summary>
		/// 
		/// </summary>
        public new IEconomyStatus this[string myID]
		{
			get
			{
				for(int i = 0; i < this.items.Count; i ++)
				{
                    IEconomyStatus myPf = this[i] as IEconomyStatus;
                    if (myPf.ID == myID)
						return myPf;
				}
				return null;
			}
		}
        public new IEconomyStatus this[int index]
		{
			get
			{
				try
				{
					if ((index >= 0) && (index < this.items.Count))
					{
						object o = base[index];
                        return o as IEconomyStatus;
					}
					else
					{
						return null;
					}
				}
				catch
				{
                    Debug.Assert(false, "IEconomyStatus : Error getting IEconomyStatus");
					return null;
				}
			}
			set
			{
				if ((index >= 0) && (index < this.items.Count))
				{
					base[index] = value;
				}
			}
		}
	

		#endregion


        /// <summary>
        /// name convention for portfolios: Contain the Trader name!!! Economy_Portfolio1
        /// </summary>
        /// <returns></returns>
        public override bool Serialize()
        {
            this.ResetPathFromConfiguration();

            for(int i = 0; i < this.items.Count; i++)
            {
                EconomyStatus myPf = this[i] as EconomyStatus;
                myPf.ResetPathFromConfiguration();
                myPf.Serialize();
            }
            return true;

        }

   


        /// <summary>
        /// name convention for portfolios: Contain the Trader name!!! Economy_Portfolio1
        /// </summary>
        /// <returns></returns>
        public override object DeSerialize()
        {
            try
            {
                if (this.items.Count > 0)
                    this.items.RemoveRange(0, this.items.Count - 1);


                //Check ID!
              
                ProgramContext dh = ProgramContext.Instance;
                string path = dh.Configuration.Directories.EconomyStatusPath;

                //search for all portfolios:

                //-------------------------------------------
                //search for files in that dir
                System.IO.DirectoryInfo di = new DirectoryInfo(path);
                if (!System.IO.Directory.Exists(path))
                    System.IO.Directory.CreateDirectory(path);

                dh.Logfile.WriteTimeSpanLog("   Reading IEconomyStatus Directory: " + path);

                foreach (FileInfo file in di.GetFiles("*.xml"))
                {

                    string strFile = file.Name;

                    string idPortfolio = CUtil.IOUtil.CutRightFourChars(strFile);
                    //string id = CUtil.IOUtil.ExtractBetween_(idPortfolio, 0);



                    if (!String.IsNullOrEmpty(idPortfolio))
                    {
                        IEconomyStatus portf = new EconomyStatus();
                        portf.ID = idPortfolio;

                        object o = new EconomyStatus();

                        if (portf.DeSerialize(ref o))
                        {
                            portf = o as EconomyStatus;
                            this.Add(portf);
                            dh.Logfile.WriteTimeSpanLog("       -success deserializing EconomyStatus: " + idPortfolio);
                        }
                    }

                }
                this.Sort();
            }
            catch (Exception ex)
            {
                Debug.Assert(false, "Error Deserialize EconomyStatusCollection: " + ex.Message);
            }
            
            return new object();

        }
        public int Evaluate_NumberOfShares()
        {
            int number = 0;
            for (int i = 0; i < this.Items.Count; i++)
            {
                IPortfolio portfolio = this[i] as IPortfolio;
                number += portfolio.DataItems.Count;

            }
            return number;

        }
        public double Evaluate_Shares_Money()
        {
            //int NumberOfShares = this.Evaluate_NumberOfShares();

            double moneyShares = 0F;
            for (int i = 0; i < this.Items.Count; i++)
            {
                IPortfolio portf = this[i] as IPortfolio;
                moneyShares += portf.Value_TotalUpdate;
            }
            Debug.WriteLine("Money Shares = " + moneyShares);
            return moneyShares;
        }
        public double Evaluate_Shares_Money(DateTime date)
        {
            double money = 0;
            for (int i = 0; i < this.Items.Count; i++)
            {
                IDataItem di = this[i] as IDataItem;
                IDataClass dc = di.DataClass;

                IQuoteBase q = dc.QuoteCollection[date] as IQuoteBase;
                double moneyClass = di.Number * q.CLOSEc;
                Debug.WriteLine("Value of share " + dc.ID + " is = " + moneyClass.ToString());
                money += moneyClass;


            }

            return money;

        }
     
        /// <summary>
        /// ToPortfolioItemArray
        /// </summary>
        /// <returns></returns>
        public Portfolio[] ToPortfolioItemArray()
		{
			try
			{
                return (Portfolio[])this.items.ToArray(typeof(Portfolio));
			}
			catch (Exception exc)
			{
				Debug.WriteLine("DataItems - Error creating PortfolioItemArray" + exc.Message);
			}
			return null;
		}
        /// <summary>
        /// a problem will be the Shares_Intraday and Shares_Daily split - try to change it ...
        /// 
        /// </summary>
        /// <param name="shareNumbers"></param>
        /// <returns></returns>
        public bool Create_TestData(double moneyEconomy, int numberOfShareValues)
        {
            double moneyLeft = moneyEconomy;

            //int numberOfShares = this.Evaluate_NumberOfShares();
            double moneyPerItem = 0F;
            //if(numberOfShares != 0)
            //    moneyPerItem = moneyLeft / numberOfShares;

            int numberOfPortfolios = this.Items.Count;
            if (numberOfPortfolios != 0)
                moneyPerItem = moneyLeft / numberOfPortfolios;
            double randomMoney = 0;
            IPortfolio portfolio = null;
            for (int i = 0; i < this.Items.Count; i++)
            {
                portfolio = this[i] as IPortfolio;
                //one share per portfolio
                randomMoney = RandomGenerator.Random(1, Convert.ToInt32(moneyPerItem));
                moneyLeft -= randomMoney;
                //portfolio.Money = randomMoney;
                portfolio.Create_TestData(numberOfShareValues);

                //CreateShareWithOneValue(randomMoney, portfolio);



            }
            //the first share will take the rest!
            portfolio = this[0] as IPortfolio;
            if (portfolio != null)
            {
                //portfolio.Money = randomMoney;
                portfolio.Create_TestData(numberOfShareValues);
                //CreateShareWithOneValue(Convert.ToInt32(moneyLeft), portfolio);
            }

            return true;

        }
        public static System.Collections.Specialized.StringCollection Create_PortfolioNames()
        {
            System.Collections.Specialized.StringCollection pn = new System.Collections.Specialized.StringCollection();


            pn.Add("Economy_Bunds");
            pn.Add("Economy_Chemistry");
            pn.Add("Economy_Cars");
            pn.Add("Economy_Food");
            pn.Add("Economy_IT");

            return pn;

        }

        public bool Create_Default()
        {
            //empty portfolios!!!

            //System.Collections.Specialized.StringCollection pn = Create_PortfolioNames();
            string portfName = "Default";

            IPortfolioFactory pf = new PortfolioFactory();

            pf.Create(portfName);
            pf.Create_Default();
            IPortfolio portfolio = pf.StockObjectBase as IPortfolio;


            portfolio.ID = portfName;
            //portfolio.CreateTestData();
            this.Items.Add(portfolio);



            return true;




        }
   
        public bool Create_TestData()
        {
            //empty portfolios!!!

            System.Collections.Specialized.StringCollection pn = Create_PortfolioNames();

            if (pn != null)
            {
                IPortfolioFactory pf = new PortfolioFactory();
                for (int i = 0; i < pn.Count; i++)
                {
                    pf.Create(pn[i]);
                    pf.Create_TestData();
                    IPortfolio portfolio = pf.StockObjectBase as IPortfolio;

                    //IPortfolio portfolio = new Portfolio();
                    //portfolio.ID = pn[i];
                    portfolio.ID = pn[i];
                    //portfolio.CreateTestData();
                    this.Items.Add(portfolio);

                }

                return true;
            }


            return false;


        }

        public new IEconomyStatusCollection Clone()
        {
            IEconomyStatusCollection myColl = new EconomyStatusCollection();
            for (int i = 0; i < this.Items.Count; i++)
            {
                myColl.Items.Add(this.Items[i]);
            }
            return myColl;
           
        }
	}
}
